package Sort;

import java.util.Arrays;
import java.util.Comparator;
import java.util.PriorityQueue;

public class HeapSort {
    public static void main(String[] args) {
        int[] arr = {10,4,2,3,5,7,8,9};
        heapSort(arr);
        System.out.println(Arrays.toString(arr));
    }
    public static void heapSort(int[] array) {
        Heap heap = new Heap(array);
    }

}
class Heap {
    int[] arr;
    int size;

    public Heap(int[] arr) {
        this.arr = arr;
        size = arr.length;
        buildHeap(arr,size);
        heapSort(arr);
    }

    public void down(int i, int size) {
        int left = i*2+1;
        int right = left+1;
        int max = i;
        if (left < size && arr[left] > arr[max]) {
            max = left;
        }
        if (right < size && arr[right] > arr[max]) {
            max = right;
        }

        if (max != i) {
            swap(arr,max,i);
            down(max,size);
        }

    }
    public void swap(int[] arr,int i,int j) {
        int temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
    }

    public void buildHeap(int[] arr,int size) {

        for (int i = size / 2 - 1; i >= 0 ; i--) {
            down(i,size);
        }
    }

    public void heapSort(int[] arr) {
        int n = arr.length - 1;
        for (int i = n; i > 0; i--) {
            swap(arr,i,0);
            down(0,i);
        }
    }
}
